<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/actions/admin/AdminAction.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/actions/Response.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/Service.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/entities/Post.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/const/Error.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/const/Pattern.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/utils/Str.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/ServiceFactory.php';

final class PostUpdateAction extends AdminAction {
	protected function execute(Response $response) {
		$post = null;
		if(isset($_POST['name']) && Str::isMatch(Pattern::WORDS, $_POST['name'])) {
			$post = new Post();
			$post->setName($_POST['name']);
			if(isset($_POST['unique'])) {
				$post->setUnique(true);
			}else{
				$post->setUnique(false);
			}
			$serviceFactory = new ServiceFactory();
			$service = $serviceFactory->getService('PostService');
			if(isset($_POST['identity'])) {
				$post->setIdentity($_POST['identity']);
			} 
			$post = $service->save($post);
			if($post === null) {
				$response->setError(Error::UNIQUE_POST_ERROR);
			}
		}
		if($response->getError() === null) {
			if($post !== null) {
				$_SESSION['post-identity'] = $post->getIdentity();
				$response->setActionPath('/post/edit.html');
			} else {
				$response->setActionPath('/post/index.html');
			}
		}
	}
}
?>